<?php

class RelexDB {
	public static $LEVEL_ROOT = -1;
	public static $LEVEL_ARTICLE = 7;

	private $dbh;
	private $q_law;
	private $q_art;


	public function __construct() {
		$dbh = new PDO("pgsql:dbname=relex;host=localhost;user=relex;password=relex");
		$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$this->q_law = $dbh->prepare(
			"SELECT lp.id AS id, lp.partno AS partno, lt.body AS body " .
			"FROM lexdoc l " .
			"INNER JOIN lexpart lp ON lp.doc_id = l.id " .
			"INNER JOIN lexparttext lt ON lt.part_id = lp.id " .
			"WHERE l.id = :docid " .
			"AND lt.language = :lang " .
			"AND TO_DATE(:date, 'YYYY-MM-DD') " .
			"	BETWEEN lp.validfrom AND COALESCE(lp.validtill, '2100-01-01') " . 
			"ORDER BY seqno ");

		$q_art = $dbh->prepare(
			"SELECT lp.id AS id, lp.partno AS partno, lt.body AS body " .
			"FROM lexpart lp ON lp.doc_id = l.id " .
			"INNER JOIN lexparttext lt ON lt.part_id = lp.id " .
			"INNER JOIN lexparttype lpt ON lpt.id = lp.parttype_id " .
			"WHERE lp.doc_id = :docid " .
			"AND lpt.levelno = 7 ".
			"AND lp.partno = :partno " .
			"AND TO_DATE(:date, 'YYYY-MM-DD') " .
			"	BETWEEN lp.validfrom AND COALESCE(lp.validtill, '2100-01-01') " . 
			"AND lt.language = :lang "); 
	}

	public function getLaw($docid, $lang, $date) {
		$this->q_law->execute(
			array(':docid' => $docid, ':lang' => $lang, ':date' => $date));
		return $this->q_law;
	}

	public function getArticle($docid, $partno, $lang, $date) {
		return $q_art->execute(
			array(	':docid' => $docid, ':partno' => $partno, 
					':lang' => $lang, ':date' => $date));
	}
}

?>
